import request from './request'
import { RESOURCE_BASE_URL } from '@/config'

interface UploadResponse {
  success: boolean
  message: string
}

interface UserMusic {
  id: string
  title: string
  artist: string
  cover: string
  duration: string
  url: string
  lrc: string
  createTime?: string
}

interface UserMusicResponse {
  success: boolean
  message: string
  data: UserMusic[]
}

/**
 * 上传音乐
 * @param formData 包含音乐信息的FormData对象
 * @returns Promise<{ success: boolean, message: string }>
 * 
 * formData应包含:
 * - title: string        音乐标题（必需）
 * - artist: string       艺术家（必需）
 * - musicFile: File      音乐文件（必需）
 * - coverFile: File      封面图片（可选）
 * - lyricFile: File      歌词文件（可选）
 */
export const uploadMusic = async (formData: FormData): Promise<UploadResponse> => {
  try {
    const response = await request.post('/resource/upload-music', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    return response.data
  } catch (error: any) {
    console.error('上传音乐失败:', error)
    // 处理特定错误状态
    if (error.response?.status === 401) {
      return {
        success: false,
        message: '请先登录'
      }
    }
    if (error.response?.status === 400) {
      return {
        success: false,
        message: '请检查必填项是否完整'
      }
    }
    return {
      success: false,
      message: '上传失败'
    }
  }
}

/**
 * 删除音乐
 * @param id 音乐ID
 * @returns Promise<{ success: boolean, message: string }>
 */
export const deleteMusic = async (id: string): Promise<{ success: boolean, message: string }> => {
  try {
    const response = await request.delete(`/resource/${id}`)
    return response.data
  } catch (error: any) {
    console.error('删除音乐失败:', error)
    // 处理特定错误状态
    if (error.response?.status === 401) {
      return {
        success: false,
        message: '请先登录'
      }
    }
    if (error.response?.status === 403) {
      return {
        success: false,
        message: '您没有权限删除该音乐'
      }
    }
    if (error.response?.status === 404) {
      return {
        success: false,
        message: '音乐不存在'
      }
    }
    return {
      success: false,
      message: '删除失败'
    }
  }
}

/**
 * 获取用户上传的音乐列表
 * @returns Promise<UserMusicResponse>
 */
export const getUserMusic = async (): Promise<UserMusicResponse> => {
  try {
    const response = await request.get<UserMusicResponse>('/resource/my-music')
    
    // 使用 RESOURCE_BASE_URL 处理图片 URL
    if (response.data.success && response.data.data) {
      response.data.data = response.data.data.map(music => ({
        ...music,
        cover: music.cover ? `${RESOURCE_BASE_URL}/${music.cover.startsWith('/') ? music.cover.slice(1) : music.cover}` : ''
      }))
    }
    
    return response.data
  } catch (error: any) {
    console.error('获取用户音乐列表失败:', error)
    if (error.response?.status === 401) {
      return {
        success: false,
        message: '请先登录',
        data: []
      }
    }
    return {
      success: false,
      message: '获取列表失败',
      data: []
    }
  }
}
